<?php

class Gallery_Backend_Photos_List extends Backend_Component_List 
{
    
    /**
     * Количество записей, выводимых на странице. Хочешь включить разбиение —
     * укажи, по сколько записей разбивать.
     *
     * @var integer
     */
    protected $_per_page = 12;
    
    /**
     * Path to the template file.
     *
     * @var string
     */
    protected $_template = 'gallery/backend/photos/container.tpl';
    
    /**
     * @desc Define table in case of automatic build for SQL statement. 
     *
     * @param string
     */
    protected $_table = 'photos';
    
    /**
     * @desc List columns. 
     *
     * @param array
     */
    protected $_columns = array('file', 'title', 'tags_list', 'added_at');
    
    /**
     * @desc SQL ORDER field. 
     *
     * @param string
     */
    protected $_order = 'added_at';
    
    /**
     * @desc Fields' list for which reverse order is held. 
     *
     * @param array
     */
    protected $_reverse = array('added_at');
    
    /**
     * @desc Form SQl statement. 
     *
     * @return  string
     */
    protected function _getQueryBody()
    {
        $this->_setAlbumTitle();
        
        $ids = array();
        $this->_getCategoriesIds(Kernel_Util_Tree::children(
            Gallery_Backend_Utils::getCategories(), $this->_activeFilter()), $ids);
        $ids[] = $this->_activeFilter();
        
        $query = '
            SELECT SQL_CALC_FOUND_ROWS
                         *,
						 "tags_list"
                    FROM
                         `photos`
                   WHERE
                         `category_id` ' . (empty($ids) 
                                            ? ' = ' . $this->_activeFilter() 
                                            : 'IN (' . implode(', ', $ids) . ')');

        return $query .= $this->_getOrder();
    }
    
    private function _getCategoriesIds(array $categories = array(), array &$ids = array()) 
    {
        foreach ($categories as $category) {
            $ids[] = $category['id'];
            if (!empty($category['children'])) {
                $this->_getCategoriesIds($category['children'], $ids);
            }
        }
    }
    
    /**
     * @desc User processing. 
     *
     */
    protected function _process() 
    {
        parent::_process();
        
        
        $response = Application::getResponse();
        
        $entries = $response->getVars('entries');
		$image_box = array();
		$photo_ids = array();


        foreach ($entries as $entry) {
            $image_box[$entry['id']] = array
            (
                'img' => BASE_PATH . Kernel_Config::get('gallery', 'photo_sorage') . '/' . $entry['file'], 
                'name' => $entry['title'], 
                'text' => nl2br($entry['description']), 
                'info' => nl2br($entry['remark']), 
            );
			$photo_ids[] = $entry['id'];
        }
		$tags = $this->_getTags($photo_ids);
		
        $response->assign(array(
            'image_box' => json_encode($image_box),
			'url' => Application::getRequest()->url(),
			'tags' => $tags,
			'tags_image_box' => json_encode($tags),
        ));
    }

	private function _getTags(array $photo_ids = array())
	{
		if (empty($photo_ids)) {
			return array();
		}
		
		$query = '
			SELECT
					`p_2_t`.`photo_id`,
					`p_t`.`id`,
					`p_t`.`name`
			FROM
					`photos_2_tags` `p_2_t`
			INNER JOIN
					`photo_tags` `p_t`
			ON
					`p_t`.`id` = `p_2_t`.`tag_id`
			WHERE
					' . database::values(array('photo_id' => $photo_ids)) . '
			ORDER BY
					`p_t`.`name` ASC
		';

		$entries = array();
		foreach (database::fetchAll($query) as $entry) {
			$entries[$entry['photo_id']][] = array_slice($entry, 1);
		}
		return $entries;
	}
    
    /**
    * Return active filter value
    * 
    * @return integer
    */
    protected function _activeFilter() 
    {
        return Gallery_Backend_Utils::activeFilter();
    }
    
    /**
    * Set album title
    * 
    * @param string $title
    */
    protected function _setAlbumTitle() 
    {
        foreach (Gallery_Backend_Utils::getCategories() as $entry) {
            if (Gallery_Backend_Utils::activeFilter() == $entry['id']) {
                Application::getResponse()->setTitle($entry['name']);
            }
        }
    }
    
}